/*
 * @Author: lizhil
 * @Date: 2020-11-30 13:38:01
 * @Last Modified by: lizhil
 * @Last Modified time: 2021-12-13 16:33:57
 */
module.exports = () => {
  return async (ctx, next) => {
    const start = new Date().getTime()

    const { RequestLog } = ctx.model

    await next()

    const end = new Date().getTime()

    const { request, session } = ctx

    const data = {
      // ip: ctx.ip,
      ip: ctx.headers['x-real-ip'],
      url: request.url,
      method: request.method,
      body: request.body,
      query: request.query,
      // session: session,
      headers: ctx.headers,
      responseTime: end - start,
      status: ctx.status,
    }

    if (ctx.exception) {
      if (ctx.exception.stack) data.stack = ctx.exception.stack
    }

    // 记录错误
    if (ctx.status != 200 && ctx.status != 304) data.response = ctx.body
    else {
      if (typeof ctx.body == 'object' && ctx.body.code) {
        data.apiCode = ctx.body.code
        if (ctx.body.code != 0) data.response = JSON.stringify(ctx.body)
      }
    }

    RequestLog.create(data)
  }
}
